#include <53func.h>
typedef struct shareRes_s {
    int ticket;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void * sellWindow1(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pShareRes->mutex);
        if(pShareRes->ticket <= 0){
            pthread_mutex_unlock(&pShareRes->mutex);
            break;
        }
        printf("Before window1 sell, ticket = %d\n", pShareRes->ticket);
        --pShareRes->ticket;
        printf("After window1 sell, ticket = %d\n", pShareRes->ticket);
        if(pShareRes->ticket < 10){
            pthread_cond_signal(&pShareRes->cond);
        }
        pthread_mutex_unlock(&pShareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void * sellWindow2(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    while(1){
        pthread_mutex_lock(&pShareRes->mutex);
        if(pShareRes->ticket <= 0){
            pthread_mutex_unlock(&pShareRes->mutex);
            break;
        }
        printf("Before window2 sell, ticket = %d\n", pShareRes->ticket);
        --pShareRes->ticket;
        printf("After window2 sell, ticket = %d\n", pShareRes->ticket);
        if(pShareRes->ticket < 10){
            pthread_cond_signal(&pShareRes->cond);
        }
        pthread_mutex_unlock(&pShareRes->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
void * addTicket(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pShareRes->mutex);
    if(pShareRes->ticket >= 10){
        pthread_cond_wait(&pShareRes->cond,&pShareRes->mutex);
    }
    printf("Tickets are not enough now!\n");
    pShareRes->ticket += 10;
    pthread_mutex_unlock(&pShareRes->mutex);
    pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
    shareRes_t shareRes;
    shareRes.ticket = 20;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);

    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1,NULL,sellWindow1,&shareRes);
    pthread_create(&tid2,NULL,sellWindow2,&shareRes);
    pthread_create(&tid3,NULL,addTicket,&shareRes);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    return 0;
}

